<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>订单管理</span>
        <el-button type="primary" @click="openCreateOrderDrawer">新增订单</el-button>
      </div>
    </template>
    <el-table :data="tableData" stripe :height="600" style="width: 100%">
      <el-table-column prop="id" label="订单ID"/>
      <el-table-column prop="userId" label="用户ID"/>
      <el-table-column prop="hotelName" label="酒店名称"/>
      <el-table-column prop="roomType" label="房型"/>
      <el-table-column prop="amount" label="金额"/>
      <el-table-column prop="paymentMethod" label="支付方式"/>
      <el-table-column label="创建时间">
        <template #default="{ row }">
          {{ formatDate(row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="退房时间">
        <template #default="{ row }">
          <el-tooltip effect="dark" placement="top" v-if="row.checkoutTime || row.checkout_time">
            <template #content>{{ formatDate(row.checkoutTime || row.checkout_time) }}</template>
            <span>{{ formatDate(row.checkoutTime || row.checkout_time) }}</span>
          </el-tooltip>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="订单状态">
        <template #default="{ row }">
          <el-tag type="info" v-if="row.cancelTime">已取消</el-tag>
          <el-tag type="warning" v-else-if="!row.payTime">未支付</el-tag>
          <el-tag type="success" v-else-if="row.checkoutTime || row.checkout_time">已退房</el-tag>
          <el-tag type="primary" v-else>已支付</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280px">
        <template #default="{ row }">
          <!-- 未支付且未取消的订单可以支付 -->
          <el-button v-if="!row.payTime && !row.cancelTime" type="success" size="small" @click="handlePay(row)">支付</el-button>
          <!-- 未支付且未取消的订单可以取消 -->
          <el-button v-if="!row.payTime && !row.cancelTime" type="warning" size="small" @click="handleCancel(row)">取消</el-button>
          <!-- 已支付且未退房的订单可以退房 -->
          <el-button v-if="row.payTime && !(row.checkoutTime || row.checkout_time) && !row.cancelTime" type="primary" size="small" @click="handleCheckout(row)">退房</el-button>
          <el-button type="danger" size="small" @click="handleDelete(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-box">
      <el-pagination background layout="total, sizes, prev, pager, next"
                     v-model:current-page="pageIndex"
                     v-model:page-size="pageSize"
                     :page-sizes="[10, 20, 50, 100]"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :total="total"/>
    </div>
    <create-order ref="createOrderRef" @refresh="initData"/>
    
    <!-- 支付订单对话框 -->
    <el-dialog v-model="payDialogVisible" title="支付订单" width="30%">
      <el-form :model="payForm" label-width="100px">
        <el-form-item label="订单ID">
          <el-input v-model="payForm.orderId" disabled />
        </el-form-item>
        <el-form-item label="酒店名称">
          <el-input v-model="payForm.hotelName" disabled />
        </el-form-item>
        <el-form-item label="房型">
          <el-input v-model="payForm.roomType" disabled />
        </el-form-item>
        <el-form-item label="金额">
          <el-input v-model="payForm.amount" disabled>
            <template #append>¥</template>
          </el-input>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-input v-model="payForm.createTime" disabled />
        </el-form-item>
        <el-form-item label="支付方式">
          <el-select v-model="payForm.paymentMethod" placeholder="请选择支付方式" style="width: 100%">
            <el-option label="支付宝" value="支付宝"/>
            <el-option label="微信" value="微信"/>
            <el-option label="信用卡" value="信用卡"/>
            <el-option label="现金" value="现金"/>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="payDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmPay">确认支付</el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>
<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { getOrderList, deleteOrder, payOrder, cancelOrder, checkoutOrder } from '@/api/order'
import { Edit, Delete } from '@element-plus/icons-vue'
import CreateOrder from './components/CreateOrder.vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const tableData = ref([])
const total = ref(0)
const pageIndex = ref(1)
const pageSize = ref(20)
const createOrderRef = ref()

// 支付订单相关
const payDialogVisible = ref(false)
const payForm = reactive({
  orderId: '',
  paymentMethod: '支付宝',
  hotelName: '',
  roomType: '',
  amount: '',
  createTime: ''
})

// 格式化日期
const formatDate = (dateStr: string | null) => {
  if (!dateStr) return '-';
  const date = new Date(dateStr);
  return date.toLocaleString();
};

const initData = () => {
  console.log('开始获取订单列表数据...');
  
  getOrderList().then(res => {
    console.log('获取订单列表响应:', res);
    
    // 正确处理后端响应
    const result = res.data;
    console.log('后端返回的原始数据结构:', result);
    
    if (result && result.code === 200) {
      // 直接使用后端返回的数据
      tableData.value = Array.isArray(result.data) ? result.data : [];
      total.value = tableData.value.length;
      
      // 处理字段名称差异
      tableData.value = tableData.value.map(item => {
        // 确保数据一致性，处理可能的checkoutTime/checkout_time命名差异
        if (item && item.checkout_time && !item.checkoutTime) {
          item.checkoutTime = item.checkout_time;
        }
        return item;
      });
      
      console.log('处理后的订单数据:', tableData.value);
      
      // 检查数据结构中的字段名
      if (tableData.value.length > 0) {
        console.log('第一条订单数据的字段名:', Object.keys(tableData.value[0]));
        // 检查是否有退房时间字段
        console.log('checkoutTime 字段是否存在:', tableData.value.some(item => 'checkoutTime' in item));
        console.log('checkout_time 字段是否存在:', tableData.value.some(item => 'checkout_time' in item));
        // 检查一条退房订单数据
        const checkoutOrder = tableData.value.find(item => item.checkoutTime || item.checkout_time);
        console.log('有退房时间的订单示例:', checkoutOrder);
      } else {
        console.log('订单列表为空');
      }
    } else {
      console.error('获取订单列表失败:', result);
      ElMessage.error(result?.msg || '获取订单列表失败');
    }
  }).catch(error => {
    console.error('获取订单列表错误:', error);
    ElMessage.error('网络错误，获取订单列表失败');
  });
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  initData()
}
const handleCurrentChange = (index: number) => {
  pageIndex.value = index
  initData()
}
const openCreateOrderDrawer = () => {
  createOrderRef.value.open()
}

// 处理支付订单
const handlePay = (row: any) => {
  payForm.orderId = String(row.id);
  payForm.paymentMethod = row.paymentMethod || '支付宝';
  payForm.hotelName = row.hotelName || '';
  payForm.roomType = row.roomType || '';
  payForm.amount = row.amount ? String(row.amount) : '';
  payForm.createTime = formatDate(row.createTime);
  payDialogVisible.value = true;
}

// 确认支付
const confirmPay = () => {
  if (!payForm.orderId) {
    ElMessage.error('订单ID不能为空');
    return;
  }
  
  if (!payForm.paymentMethod) {
    ElMessage.error('请选择支付方式');
    return;
  }
  
  console.log('准备支付订单:', payForm);
  
  payOrder({
    orderId: payForm.orderId,
    paymentMethod: payForm.paymentMethod,
    amount: payForm.amount
  }).then(res => {
    console.log('支付订单响应:', res);
    
    const result = res.data;
    if (result && result.code === 200) {
      ElMessage.success('支付成功');
      payDialogVisible.value = false;
      initData(); // 刷新列表
    } else {
      ElMessage.error(result?.msg || '支付失败');
    }
  }).catch(error => {
    console.error('支付订单错误:', error);
    ElMessage.error('网络错误，支付订单失败');
  });
}

// 处理取消订单
const handleCancel = (row: any) => {
  if (!row.id) {
    ElMessage.error('订单ID不能为空');
    return;
  }
  
  ElMessageBox.confirm('确定要取消该订单吗？', '提示', { type: 'warning' }).then(() => {
    console.log('准备取消订单:', row.id);
    
    cancelOrder(String(row.id)).then(res => {
      console.log('取消订单响应:', res);
      
      const result = res.data;
      if (result && result.code === 200) {
        ElMessage.success('取消成功');
        initData(); // 刷新列表
      } else {
        ElMessage.error(result?.msg || '取消失败');
      }
    }).catch(error => {
      console.error('取消订单错误:', error);
      ElMessage.error('网络错误，取消订单失败');
    });
  }).catch(() => {
    // 用户取消操作
    console.log('用户取消操作');
  });
}

// 处理退房
const handleCheckout = (row: any) => {
  if (!row.id) {
    ElMessage.error('订单ID不能为空');
    return;
  }
  
  ElMessageBox.confirm('确定要办理退房吗？', '提示', { type: 'warning' }).then(() => {
    console.log('准备办理退房:', row.id);
    
    checkoutOrder(String(row.id)).then(res => {
      console.log('退房响应:', res);
      
      const result = res.data;
      if (result && result.code === 200) {
        // 强制刷新数据
        setTimeout(() => {
          ElMessage.success('退房成功');
          initData(); // 刷新列表
        }, 500); // 延迟500ms刷新，确保后端数据已更新
      } else {
        ElMessage.error(result?.msg || '退房失败');
      }
    }).catch(error => {
      console.error('退房错误:', error);
      ElMessage.error('网络错误，退房失败');
    });
  }).catch(() => {
    // 用户取消操作
    console.log('用户取消退房操作');
  });
}


// 处理删除订单
const handleDelete = (id: string | number) => {
  if (!id) {
    ElMessage.error('订单ID不能为空');
    return;
  }
  
  console.log('准备删除订单:', id);
  
  ElMessageBox.confirm('确定要删除该订单吗？', '提示', { type: 'warning' }).then(() => {
    deleteOrder(String(id)).then(res => {
      console.log('删除订单响应:', res);
      
      const result = res.data;
      if (result && result.code === 200) {
        ElMessage.success('删除成功')
        initData()
      } else {
        ElMessage.error(result?.msg || '删除失败')
      }
    }).catch(error => {
      console.error('删除订单错误:', error);
      ElMessage.error('网络错误，删除订单失败');
    });
  }).catch(() => {
    // 用户取消操作
    console.log('用户取消删除操作');
  });
}

onMounted(() => {
  initData()
})
</script>
<style scoped>
.header { display: flex; justify-content: space-between; align-items: center; }
.pagination-box { padding-top: 16px; display: flex; justify-content: right; }
</style>
